import React from "react";
import { connect } from "dva";
import classnames from "classnames";
import { Form, Input, message } from "antd";
import {uploadImgBase64, uploadOssImg } from "../../services/fetch";
import { localUrl} from "../../utils/index";
import { guid } from "../../utils/Date";
import "./Video-mon.less";
import VideoPlayer from "../../components/VideoPlayer/VideoPlayer";

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(({ add }) => ({ add: add }))
@Form.create({})
class AddVideo extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      videoError: false,
      imgError: false,
      loadingVideo: false,
      VideoUrl: "",
      imageUrl: "",
      percentVideo: 0,
      percentImage: 0,
      currentHive: "",
      marginLeft: 0,
      marginRight: 0
    };
  }
  componentDidMount() {
    this.props.onRef(this);
  }
  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 上传插件
   */
  fcUpload = key => {
    window.fc = null;
    let type;
    let maxSize = 2000;
    if (key === "video_src") {
      type = "video";
    } else if (key === "video_img") {
      type = "img";
      maxSize = 2;
    }
    window.fc = new window.FcUpload({
      elem: "fcUpload" + type,
      multiple: false, //是否允许上传多个文件
      type: type, // 上传文件类型\ img 图片，  video 视频
      host:localUrl,
      actionImg: `${localUrl}/fcpublic/uploads/uploadImg`, //本地上传图片地址
      actionVideo: `${localUrl}/fcpublic/uploads/uploadVideo`, //本地上传视频地址
      callback: callRes => {
        const formValues = this.props.form.getFieldsValue();
        if (!formValues.video_title) {
          //视频标题自动生成
          this.props.form.setFieldsValue({
            video_title: callRes.file.name.split(".")[0]
          });
        }
        let url;
        if (callRes.oss) {
          // oss 和本地返回数据结构不一样
          url = callRes.response[0];
        } else {
          if (key === "video_src") {
            url = callRes.response[0].data.video_path;
          } else if (key === "video_img") {
            url = callRes.response[0].data;
          }
        }
        let obj = {};
        obj[key] = url;
        this.props.form.setFieldsValue(obj);
        let storeAs = guid();
        let nowDate = new Date();
        let year = nowDate.getFullYear();
        let month = nowDate.getMonth() + 1;
        let day = nowDate.getDate();
        let new_url = "transcode/" + year + "/" + month + "/" + day + "/" + storeAs;
        if (this.props.add.configJson.materialRootDirectory) {
          new_url = this.props.add.configJson.materialRootDirectory + "/" + new_url;
        }
        let http = document.location.protocol + "//" + this.props.add.configJson.bucket + "." + this.props.add.configJson.endpoint + "/";
        let old_url = url.replace(http, "");
        if (this.props.add.configJson.customDomain) {
          old_url = old_url.replace(this.props.add.configJson.customDomain + "/", "");
          old_url = old_url.replace(this.props.add.configJson.customDomain, "");
        }
        let arr = old_url.split(".");
        if (type === "video") {
          this.setState({
            is_update: 1
          });
          this.props.dispatch({
            type: "add/setFields",
            data: {
              is_update: 1 //视频是否重新上传
            }
          });
          // this.loadNewVideo();
        }
        // let videoDom = document.getElementById("video_src");
        // videoDom.oncanplay = ()=>{
        //
        // };
        //转码
        if (this.props.add.configJson.aliyunOssSwitch && this.props.add.configJson.aliyunTranscodeSwitch) {
          if (type === "video") {
            let postData = {
              oss_bucket: this.props.add.configJson.bucket,
              oss_input_object: old_url,
              oss_output_object: new_url + "." + arr[1]
            };
            this.props.dispatch({
              type: "add/setFields",
              data: {
                transcode_data: postData
              }
            });
          }
        }
      }
    });
    window.fc.show();
  };

  /**
   * 视频截图
   */
  snapScreen = () => {
    message.loading("截图生成中...");
    setTimeout(() => {
      const $canvas = window.document.getElementById("CutCanvas");
      const $video = window.document.getElementById("video_src").children[0];
      if (!$video) {
        message.error("请先上传视频");
        return false;
      }
      // $video.play();
      var videoWidth = $video.videoWidth > 0 ? $video.videoWidth : 295;
      var videoHeight = $video.videoHeight > 0 ? $video.videoHeight : 165;
      var width = videoWidth > 640 ? 640 : videoWidth;
      var height = videoHeight * (width / videoWidth);
      $canvas.width = width;
      $canvas.height = height;
      var ctx = $canvas.getContext("2d"); //创建画布

      ctx.drawImage($video, 0, 0, width, height); //将视频写入canvas
      let data = $canvas.toDataURL("images/png"); //
      uploadImgBase64({ img: data }).then(res => {
        if (res.data.code === 200) {
          if (this.props.add.configJson.aliyunOssSwitch) {
            uploadOssImg({ file: res.data.data }).then(res2 => {
              if (res2.data.code === 200) {
                this.setState({
                  imageUrl: res2.data.data,
                  loading: false,
                  imgError: false
                });
                this.props.form.setFieldsValue({
                  video_img: res2.data.data
                });
              } else {
                this.setState({
                  imageUrl: res.data.data,
                  loading: false,
                  imgError: false
                });
                this.props.form.setFieldsValue({
                  video_img: res.data.data
                });
              }
            });
          } else {
            this.setState({
              imageUrl: res.data.data,
              loading: false,
              imgError: false
            });
            this.props.form.setFieldsValue({
              video_img: res.data.data
            });
          }
        }
      });
    }, 1000);
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.forEach((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["img_arr"] = this.state.imgList;
    data["type"] = 2;
    return data;
  };
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();
    this.props.form.validateFields();
    let validateArr = this.props.form.getFieldsError();
    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.forEach((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["img_arr"] = this.state.imgList;
      data["type"] = 2;
      return data;
    }
  };
  /**
   * 设置值
   */
  setFields = data => {
    // let formData = this.props.form.getFieldsValue();
    let setData = {};
    setData.video_title = data.title;
    setData.receive_site = data.push_site;
    setData.video_intro = data.summary;
    setData.video_src = data.url;
    setData.key_word = data.keyword;
    setData.external_links = data.external_links || "";
    this.props.form.setFieldsValue(setData);
  };
  render() {
    const imageUrl = this.props.form.getFieldValue("video_img");
    const VideoUrl = this.props.form.getFieldValue("video_src");
    const ext = VideoUrl
      ? VideoUrl.split(".")
          .pop()
          .toLowerCase()
      : "mp4";
    const videoJsOptions = {
      autoplay: false,
      controls: true,
      height: 165,
      width: 295,
      loop: false,
      // playbackRates: [0.5, 1, 1.5, 2],
      sources: [
        {
          src: VideoUrl,
          type: ext == "m3u8" ? "application/x-mpegURL" : "video/mp4"
        }
      ],
      isUpdate: this.state.is_update //是否新建视频触发截图
    };
    const {
      form: { getFieldDecorator }
    } = this.props;
    let video_title = this.props.form.getFieldValue("video_title");
    video_title = video_title ? video_title : "";

    let video_intro = this.props.form.getFieldValue("video_intro");
    video_intro = video_intro ? video_intro : "";

    const titleSuffix = <span className={classnames("titleLength", { red: video_title.length > 60 })}>{video_title.length}/60</span>;

    const introSuffix = <span className={classnames("introtitleLength", { red: video_intro.length > 2000 })}>{video_intro.length}/2000</span>;

    let key_word = this.props.form.getFieldValue("key_word");
    key_word = key_word ? key_word : "";

    const keyWordSuffix = <span className={classnames("titleLength", { red: key_word.length > 50 })}>{key_word.length}/50</span>;

    this.props.onRef(this);
    // const formValues = this.props.form.getFieldsValue();
    return (
      <div className="VideoMon">
        <Form className="form" onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
        <FormItem className="form_item mon_text1" label="">
          {getFieldDecorator("video_title")(
            // <Input 
            //   prefix={<span className="red">*</span>} 
            //   suffix={titleSuffix}
            //   className="subject"
            //   placeholder="请输入标题" 
            //   maxLength={60} 
            // />
            <div className="title_form_box">
              <div className="title">ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ</div>
              <Input 
                prefix={<span className="red">*</span>} 
                // suffix={titleSuffix}
                className="title_input fs_18"
                placeholder="ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" 
              />
            </div>
          )}
        </FormItem>
          
        <FormItem className="form_item mon_text1" label="">
          {getFieldDecorator("key_word")(
            // <Input 
            //   className="subject keyword" 
            //   suffix={keyWordSuffix} 
            //   placeholder="请输入关键字" 
            //   maxLength={50} 
            // />

            <div className="keyword_form_box">
              <div className="keyword">ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠰᠦᠭ</div>
              <Input 
                className="keyword_input"
                placeholder="ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠰᠦᠭ᠎ᠶᠢᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" 
              />
            </div>
          )}
        </FormItem>

        <FormItem className="form_item mon_text1" label="">
          {getFieldDecorator("video_intro")(
            // <TextArea 
            //   placeholder="请输入摘要" 
            //   autosize={{ minRows: 2, maxRows: 6 }} 
            //   className="subject" 
            //   maxLength={2000} 
            // />

            <div className="abstract_form_box">
              <div className="abstract">ᠲᠣᠪᠴᠢᠯᠠᠯ</div>
              <Input 
                placeholder="ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠲᠣᠪᠴᠢᠯᠠᠯ᠎᠎ᠶᠢᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" 
                className="abstract_input" 
              />
            </div>
          )}
        </FormItem>

        <FormItem className="form_item mon_text1" label="">
          {getFieldDecorator("external_links")(
            <div className="link_form_box">
              <div className="link">ᠬᠣᠯᠪᠤᠭᠠᠰᠤ</div>
                <Input className="link_input" placeholder="ᠸᠢᠳᠢᠣ᠋᠎ᠤᠨ ᠭᠠᠳᠠᠭᠠᠳᠤ ᠬᠣᠯᠪᠤᠭᠠᠰᠤ᠎ᠪᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" />
            </div>
          )}
        </FormItem>

          <div className="upload video_upload">
            <div className="video-box">
              <div className="disc title mon_text1">
                ᠸᠢᠳᠢᠣ᠋ ᠳᠡᠭᠡᠭᠱᠢ ᠳᠠᠮᠵᠢᠭᠤᠯᠬᠤ <br></br>
                <span className="red">（2000 M᠎ᠡᠴᠡ ᠬᠡᠲᠦᠷᠡᠵᠦ ᠪᠣᠯᠬᠤ᠎ᠦᠭᠡᠢ）</span>
              </div>

              <br></br>

              <div className="video_player">
                {getFieldDecorator("video_src")(
                  <VideoPlayer
                    // snapScreen={() => {
                    //   this.snapScreen();
                    // }}
                    videoId="video_src"
                    crossOrigin="anonymous"
                    uploadVideo={() => {
                      this.fcUpload("video_src");
                    }}
                    videoJsOptions={videoJsOptions}
                  />
                )}
              </div>


              
              {/* <Button
                onClick={() => {
                  this.snapScreen();
                }}
              >
                视频截图
              </Button> */}
            </div>


            {/* <div className="image">
              <div className="title">
                封面上传<span className="red">（建议尺寸比例16：9，小于2M）</span>
              </div>
              {getFieldDecorator("video_img", {
                initialValue: `${UrlConfig}/application/fcpublic/resource/images/default.png`
              })(
                <img
                  onClick={() => {
                    this.fcUpload("video_img");
                  }}
                  src={img}
                  className="video_pic"
                  alt="封面图"
                />
              )}
            </div> */}
          </div>
        </Form>
        <canvas style={{ opacity: 0 }} id="CutCanvas"></canvas>
      </div>
    );
  }
}
export default AddVideo;
